import { HttpException, Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { Article } from "./article.entity";

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(Article)
    private ArticleRepository: Repository<Article>
  ) {}

  async findAll(userId) {
    const [list, total] = await this.ArticleRepository.findAndCount({
      where: { user: userId },
      order: { createTime: "ASC" },
      skip: 0,
      take: 1,
    });
    return { list, total };
  }

  async create(Article) {
    await this.ArticleRepository.save(Article);
    return true;
  }

  async update(id, UserTodo) {
    await this.ArticleRepository.update(id, UserTodo);
    return true;
  }

  async getOne(id) {
    const user = await this.ArticleRepository.findOne({
      where: { id, isDelete: false },
    });
    if (!user) throw new HttpException("数据不存在", 404);
    return user;
  }

  async delete(id) {
    const user = await this.getOne(id);
    await this.ArticleRepository.update(id, { ...user, isDelete: true });
    return true;
  }
}
